<!-- 离职工作交接表 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="离职交接表"
        :breadCrumb="['人事', '基础设置', '离职设置', '离职交接表']"
        show-back
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入工作交接表模板名称"
          search-button
          v-model="searchVal"
          @search="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </template>
      <template #right>
        <a-button type="primary" @click="add">新增交接表 </a-button>
        <a-button type="outline" @click="remove(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>

    <TableTurn
      ref="tableRef"
      :tableData="getData"
      style="margin-top: 20px"
      :args="args"
    >
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        title="离职交接表模板名称"
        data-index="name"
      ></a-table-column>
      <a-table-column
        :width="200"
        title="描述"
        data-index="remark"
      ></a-table-column>
      <a-table-column :width="100" title="启用状态" data-index="state">
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column :width="100" title="是否为默认" dataIndex="required">
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.default"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="26"
                @click="goPreview(record.id)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="remove(record)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <PreviewModal v-model:visible="previewVisible" :data="currData" />
  <Template
    v-model:visible="templateVisible"
    @refresh="refresh"
    :data="currData"
    :isCopy="isCopy"
  />
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
</template>
<script setup lang="ts">
import {
  GetLeaveQuitList,
  GetLeaveQuitDetail,
  DelLeaveQuitList,
  PutLeaveQuitList,
  PutLeaveQuitTemplateState,
  PostLeaveQuit,
  RepeaLeaveQuitList
} from '@/apis/management/human/baseSetting/leaveSetting';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import Template from './Components/Template/index.vue';
import { Modal } from '@arco-design/web-vue';
import PreviewModal from './Components/Preview/index.vue';

const router = useRouter();
let templateRef = ref();
const businessType = ref([
  'SER_FUNC4F34D3DCF3A24353827D56D2D1DDECE3',
  'baseComponent'
]);
let tableRef = ref(); // 储存表格的ref
let searchVal = ref(''); // 输入框的值
// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

let originData = ref(); // 储存原始数据
// 获取表格数据
const getData = async (pageData: any) => {
  try {
    const res = await GetLeaveQuitList({
      ...pageData,
      name: searchVal.value
    });
    originData.value = cloneDeep(res.content);
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 点击搜索按钮
const onSearch = () => {
  refresh();
};

// 监听键盘回车，按了回车也会查询
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    refresh();
  }
};

onMounted(() => {
  // 监听键盘事件
  window.addEventListener('keydown', keyDown);
});

const currRecord = reactive({
  data: {}
});

let templateVisible = ref(false);
// 点击新增模板按钮
const add = () => {
  // router.push({
  //   name: 'DimisssionQuizTemplate'
  // });
  currData.value = {
    baseInfo: {
      name: '',
      enable: 1,
      remark: ''
    },
    // 文件移交
    wenJian: [
      {
        name: '',
        remark: '',
        num: 1,
        superviseId: undefined, // 监督人Id
        acceptId: undefined, // 接收人Id
        type: 1,
        ownerId: undefined,
        url: ''
      }
    ],
    // 日常工作移交
    riChang: [
      {
        name: '',
        remark: '',
        num: 1,
        acceptId: undefined, // 接收人Id
        superviseId: undefined,
        type: 2,
        ownerId: undefined,
        url: ''
      }
    ],
    // 未完成待办事项
    unFinished: [
      {
        name: '',
        remark: '',
        num: 1,
        acceptId: undefined, // 接收人Id
        superviseId: undefined,
        type: 3,
        ownerId: undefined,
        url: ''
      }
    ],
    // 待办事项
    daiBan: [
      {
        name: '',
        remark: '',
        num: 1,
        superviseId: undefined,
        type: 4,
        ownerId: undefined,
        url: ''
      }
    ],
    // 资产移交
    ziChan: [
      {
        name: '',
        remark: '',
        num: 1,
        acceptId: undefined, // 接收人Id
        superviseId: undefined,
        type: 5,
        ownerId: undefined,
        url: ''
      }
    ],
    // 资源移交
    ziYuan: [
      {
        name: '',
        remark: '',
        num: 1,
        acceptId: undefined, // 接收人Id
        superviseId: undefined,
        type: 6,
        ownerId: undefined,
        url: ''
      }
    ],
    // 其他交接事项
    other: [
      {
        name: '',
        remark: '',
        num: 1,
        acceptId: undefined, // 接收人Id
        superviseId: undefined,
        type: 7,
        ownerId: undefined,
        url: ''
      }
    ]
  };
  isCopy.value = false;
  templateVisible.value = true;
};

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    // 获取更改状态之前的模板数据，并判断状态是否和当前的一样，如果一样则不能改成默认模板
    const temp = originData.value.find((item: any) => item.id === record.id);
    if (temp.default === 1) Message.error('必须拥有一个默认模板！');
    else if (temp.enable !== 1)
      Message.error('不能将未启用的模板当作默认模板!');
    else
      await PutLeaveQuitTemplateState({
        id: record.id
      });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

let currData = ref();

let previewVisible = ref(false);
const goPreview = async (id: number) => {
  currData.value = await GetLeaveQuitDetail({
    id
  });
  previewVisible.value = true;
};
// 编辑 初始化控件数据
const goEdit = async (id: number, name?: string) => {
  try {
    const res = await GetLeaveQuitDetail({
      id
    });
    currData.value = res;
    if (name) {
      isCopy.value = true;
      currData.value.baseInfo.name = name;
      handleCopyData();
    } else {
      isCopy.value = false;
    }
    templateVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
  //
};

let copyVisible = ref(false);
let currId = ref(0);
let isCopy = ref(false);
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

// // 复制
const copyEmit = async (formData: any) => {
  try {
    const res = await GetLeaveQuitDetail({
      id: currId.value
    });
    currData.value = res;
    currData.value.baseInfo.name = formData.name;
    handleCopyData();
    await PostLeaveQuit(currData.value);
    refresh();
  } catch (error) {
    console.log(error);
  }
};
// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

const handleCopyData = () => {
  delete currData.value.baseInfo.id;
  delete currData.value.baseInfo.createdAt;

  for (let i in currData.value) {
    if (i !== 'baseInfo') {
      currData.value[i].forEach((item: any) => {
        delete item.id;
        delete item.ownerId;
      });
    }
  }
};

// 批量删除
const remove = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find((item: any) => item.default === 1)
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelLeaveQuitList({
                  ids: selectedList.value,
                  type: 1 // 默认传1
                });
                tableRef.value.selectedList = [];
                tableRef.value.loadData();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.default === 1) Message.error('默认模板不能删除！');
      else {
        await DelLeaveQuitList({
          ids: [record.id],
          type: 1 // 默认传1
        });
        tableRef.value.selectedList = [];
        tableRef.value.loadData();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
</script>
<style lang="less" scoped>
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
